package com.developteam.xnmall.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.developteam.xnmall.vo.ResStatus;
import com.developteam.xnmall.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if("OPTIONS".equalsIgnoreCase(method)){
            return true;
        }
        String token = request.getHeader("token");  //受限资源的拦截器，非受限资源一续命，二全部放行
        if(token == null){
            ResultVO resultVO = new ResultVO(ResStatus.LOGIN_FAIL_NOT, "请先登录！", null);
            doResponse(response,resultVO);
        }else{
            String s = stringRedisTemplate.boundValueOps(token).get();
            if (s == null) {
                ResultVO resultVO = new ResultVO(ResStatus.LOGIN_FAIL_NOT, "请先登录！", null);
                doResponse(response,resultVO);
            } else {
                //给token续命
                stringRedisTemplate.boundValueOps(token).expire(1, TimeUnit.MINUTES);
                return true;
            }
//            try {
//                JwtParser parser = Jwts.parser();
//                parser.setSigningKey("QIANfeng6666"); //解析token的SigningKey必须和生成token时设置密码一致
//                //如果token正确（密码正确，有效期内）则正常执行，否则抛出异常
//                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
//                /*Claims body = claimsJws.getBody();//获取token中⽤户数据
//                String subject = body.getSubject(); //获取⽣成token设置的subject
//                String v1 = body.get("key1", String.class); //获取⽣成token时存储的Claims的map中的值*/
//                return true;
//            }catch (ExpiredJwtException e){
//                ResultVO resultVO = new ResultVO(ResStatus.LOGIN_FAIL_OVERDUE, "登录过期，请重新登录！", null);
//                doResponse(response,resultVO);
//            }catch (UnsupportedJwtException e){
//                ResultVO resultVO = new ResultVO(ResStatus.LOGIN_FAIL_NOT, "Token不合法，请自重！", null);
//                doResponse(response,resultVO);
//            }catch (Exception e){
//                ResultVO resultVO = new ResultVO(ResStatus.LOGIN_FAIL_NOT, "请先登录！", null);
//                doResponse(response,resultVO);
//            }
        }
        return false;
    }

    private void doResponse(HttpServletResponse response,ResultVO resultVO) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();   ////得到流输出数据
        String s = new ObjectMapper().writeValueAsString(resultVO);
        out.print(s);
        out.flush();
        out.close();
    }

}
